package com.lovepick.http;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;

import com.lovepick.GlobalApp;
import com.lovepick.util.BaseUtils;
import com.lovepick.util.Constant;


public class AvatarTask extends AsyncTask<String, Void, Bitmap>
{
	private final String TASK_TAG = "AvatarTask";
	private HttpURLConnection mUrlConnection = null;
	private URL mUrl = null;

	@Override
	protected Bitmap doInBackground(String... params)
	{
		// TODO Auto-generated method stub
		Log.i(TASK_TAG, "-----AvatarTask-----");
		String avartarId = params[0];		// 头像ID, 指的是服务器上存储的用户头像的文件名.
		String nickName = params[1];		// 用户昵称, 使用该字段对下载后的用户头像命名, 并存在本地.
		String url = Constant.HTTP_URL_AVATAR + avartarId + ".jpg";
		Log.i(TASK_TAG, "###url###\n" + url);
		InputStream in = null;
		Bitmap bitmap = null;
		try
		{
			mUrl = new URL(url);
			mUrlConnection = (HttpURLConnection)mUrl.openConnection();
			if (GlobalApp.getInstance().getCookie() != null)
			{
				Log.i(TASK_TAG, "set cookies");
				mUrlConnection.setRequestProperty("Cookie", GlobalApp.getInstance().getCookie());
			}
			mUrlConnection.setRequestMethod("GET");
			mUrlConnection.setConnectTimeout(5000);
			Log.i(TASK_TAG, "###mUrlConnection.getResponseCode()###");
			Log.i(TASK_TAG, String.valueOf(mUrlConnection.getResponseCode()));
			if (mUrlConnection.getResponseCode() == HttpURLConnection.HTTP_OK)
			{
				Log.i(TASK_TAG, "HTTP_OK");
				in = new BufferedInputStream(mUrlConnection.getInputStream());
				String cookies = mUrlConnection.getHeaderField("Cookie");
				if (cookies != null)
				{
					Log.i(TASK_TAG, "###get cookies###");
					Log.i(TASK_TAG, cookies);
				}
				if (in != null)
				{
					bitmap = BitmapFactory.decodeStream(in);
					BaseUtils.saveAvatar(nickName, bitmap);
					in.close();
				}
			}			
		}
		catch (MalformedURLException e)
		{
			// TODO Auto-generated catch block
			Log.i(TASK_TAG, "MalformedURLException!");
			e.printStackTrace();
			bitmap = null;
		}
		catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			bitmap = null;
		}
		finally
		{
			in = null;
			mUrlConnection.disconnect();
		}
		
		return bitmap;
	}
}
